from HTMLParser import HTMLParser
from urlparse import urljoin
from zipfile import ZipFile
import StringIO
import urllib2

def getresource(url):
    """
    download and return a file like object of the latest resource at the given url.
    Assumes the url will point to a list of dated zip files.
    """
    link = urllib2.urlopen(url)
    html = link.read()

    parser = AnchorParser()
    parser.feed(html)

    urlobject = urllib2.urlopen(urljoin(url, parser.lastanchor))
    return url2fileobject(urlobject)

def url2fileobject(urlobject):
    """
    return a fileobject for the given string.
    """
    return StringIO.StringIO(urlobject.read())

def unzip(fileo):
    """return a file object representation of the zipped file object."""
    z = ZipFile(fileo)
    return StringIO.StringIO(z.read(z.namelist()[0]))

class AnchorParser(HTMLParser):

    @property
    def lastanchor(self):
        return self._lastanchor

    def handle_starttag(self, tag, attrs):
        "allow some iteration through anchors in a htmlpage."
        if tag == "a":
            self._lastanchor = dict(attrs).get('href')


    def handle_endtag(self, tag):
        pass

